// pages/ShoppingCart/ShoppingCart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    UserToken: '', //用户token
    Shoppings: [], //所有购物车数据
    UserId: [], //用户id
    allocateArr: [], //选中数据
    select_all: false,
    allId: [],
    SingleCheckeAll: [],
    TotalPrice: 0, //总价格
    nowTotal:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.getStorage({
      key: 'token',
      success(res) {
        wx.request({
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          url: 'http://47.104.142.216/TP/public/index.php/index/User/VerificationToken', //本地设置不校验合法域名
          data: {
            token: res.data
          },
          method: 'POST',
          dataType: 'JSON',
          success: function (res) {
            let keys = JSON.parse(res.data)
            if (keys.errorCode == 10009) {
              wx.showToast({
                title: '您还未登录，请先登录',
                icon: 'none',
                duration: 1500
              })
              //TODO 跳转
              wx.redirectTo({
                url: '../Login/Login',
              })
            } else if (keys.errorCode == 10017) {
              wx.removeStorage({
                key: 'token',
                success(res) {
                  // console.log(res)
                }
              })
              wx.showToast({
                title: '您还未登录，请先登录',
                icon: 'none',
                duration: 1500
              })
              //TODO 跳转
              wx.redirectTo({
                url: '../Login/Login',
              })
            } else {
              //! 发送请求获取数据
              that.getCart(keys.data.user_id);
              that.setData({
                UserId: keys.data.user_id
              })
            }
          }
        })
      },
      fail: function () {
        wx.showToast({
          title: '您还未登录，请先登录',
          icon: 'none',
          duration: 1500
        })
        //TODO 跳转
        wx.redirectTo({
          url: '../Login/Login',
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 打开页面获取购物车数据
   */
  getCart: function (UserId) {
    let that = this;
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      url: 'http://47.104.142.216/TP/public/index.php/index/Cart/getCart', //本地设置不校验合法域名
      data: {
        UserID: UserId
      },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        let JsonShoppings = JSON.parse(res.data)
        if (JsonShoppings != 9) {
          JsonShoppings.forEach(tem => {
            tem.checked = false;
          })
        }
        that.setData({
          Shoppings: JsonShoppings
        })
      }
    })
  },
  /**
   * 修改物品数量提示
   */
  modifyNum: function () {
    wx.showToast({
      title: '修改数量请前往网页端',
      icon: 'none',
      duration: 1500
    })
  },
  /**
   * 删除商品
   */
  DelShopping: function (e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: function (sm) {
        if (sm.confirm) {
          //点击确定
          wx.request({
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            url: 'http://47.104.142.216/TP/public/index.php/index/Cart/DeleteCart', //本地设置不校验合法域名
            data: {
              cartId: e.currentTarget.dataset.s
            },
            method: 'POST',
            dataType: 'JSON',
            success: function (res) {
              let keys = JSON.parse(res.data)
              if (keys.errorCode == 10013) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 1500
                })
                that.getCart(that.data.UserId);
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none',
                  duration: 1500
                })
              }
            }
          })
        } else if (sm.cancel) {
          //点击取消
        }
      }
    })
  },
  /**
   * 全选
   */
  selectall: function (e) {
    const that = this;
    let allid = [];
    let list = that.data.Shoppings;
    //总价格
    let nowTotalPrice = that.data.TotalPrice;
    let nowTotal = that.data.nowTotal;
    for (let i = 0; i < list.length; i++) {
      list[i].checked = !list[i].checked || false;
      if (list[i].checked == true) {
        allid.push(list[i].cart_id);
        nowTotal += nowTotalPrice + list[i].commodity_price * list[i].cart_number;
      } else {
        allid.splice(list[i].cart_id);
        nowTotal = 0;
      }
    }
    that.setData({
      allocateArr: allid,
      Shoppings: list,
      TotalPrice: nowTotal
    })
  },
  /**
   * 多选单选
   */
  select: function (e) {
    const that = this;
    // 选中物品小计
    let selectValue = e.currentTarget.dataset.name;
    //总价格
    let nowTotalPrice = that.data.TotalPrice;
    let nowTotal;
    //购物车商品下标
    let index = e.currentTarget.dataset.index;
    let SingleCheckeAll = that.data.SingleCheckeAll;
    let Shoppings = this.data.Shoppings;
    Shoppings[index].checked = !Shoppings[index].checked; //选中变为未选中，未选中变为选中
    if (Shoppings[index].checked == true) {
      SingleCheckeAll.push(Shoppings[index].cart_id)
      nowTotal = nowTotalPrice + selectValue;
    } else if (Shoppings[index].checked == false) {
      let value = Shoppings[index].cart_id;
      SingleCheckeAll = SingleCheckeAll.filter(function(item) { 
        return item !== value
    })
      nowTotal = nowTotalPrice - selectValue;
    }
    that.setData({
      allocateArr: SingleCheckeAll,
      TotalPrice: nowTotal
    })
    console.log(that.data.allocateArr);
  },
  /**
   * 删除全选
   */
  Delall: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: function (sm) {
        if (sm.confirm) {
          //点击确定
          if (that.data.allocateArr != '') {
            wx.request({
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              url: 'http://47.104.142.216/TP/public/index.php/index/Cart/DeleAll', //本地设置不校验合法域名
              data: {
                cartId: JSON.stringify(that.data.allocateArr)
              },
              method: 'POST',
              dataType: 'JSON',
              success: function (res) {
                let keys = JSON.parse(res.data)
                if (keys.errorCode == 10015) {
                  wx.showToast({
                    title: '删除成功',
                    icon: 'success',
                    duration: 1500
                  })
                  that.getCart(that.data.UserId);
                } else {
                  wx.showToast({
                    title: '删除失败',
                    icon: 'none',
                    duration: 1500
                  })
                }
              }
            })
          } else {
            wx.showToast({
              title: '请选择商品',
              icon: 'none',
              duration: 1500
            })
          }
        } else if (sm.cancel) {
          //点击取消
        }
      }
    })
  },
  /**
   * 点击购买
   */
  toPayment: function () {
    const that = this;
    //选中商品
    let allocateArr = that.data.allocateArr;
    //总价格
    let TotalPrice = that.data.TotalPrice;
    //用户id
    let UserId = that.data.UserId;
    if (that.data.allocateArr != '') {
      wx.redirectTo({
        url: '/pages/settlement/settlement?cartId='+allocateArr+"&TotalAmount="+TotalPrice+"&UserId="+UserId,
      })
    } else {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 1500
      })
    }
  },

  /**
   * 跳转商品详情
   */
  toGoods: function(e){
    let that = this;
    let cartId = e.currentTarget.dataset.name;
    wx.redirectTo({
      url: '/pages/goods/goods?cid='+cartId,
    })
  }
})